#include<iostream>
#include<string>
#include<cstring>
#include<cassert>
#include<vector>

using std::cout;
using std::endl;
using std::cin;

#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<fcntl.h>

#include"comm.hpp"

//服务端，进行读
int main()
{
    //1. 创建管道文件
    int ret=mkfifo(fifoname.c_str(),mode);
    assert(ret==0);
    (void)ret;

    cout<<"创建管道文件成功"<<endl;
    //2. 打开管道文件
    int rfd=open(fifoname.c_str(),O_RDONLY);
    assert(rfd!=-1);
    (void)rfd;
    cout<<"以读方式打开管道文件成功"<<endl;

    //3.开始通信，接受客户端传来的信息
    char buffer[NUM]={0};
    while(true)
    {
        int n=read(rfd,buffer,sizeof(buffer)-1);
        if(n>0)
        {
            buffer[n]=0;
            //cout<<"client#"<<buffer<<endl;
            printf("%c",buffer[0]);
            fflush(stdout);
        }
        else if(n==0)
        {
            cout<<"client quit,me too"<<endl;
            break;
        }
        else
        {
            perror("read error:");
            break;
        }
    }

    ret=unlink(fifoname.c_str());
    assert(ret==0);
    (void)ret;
    cout<<"删除管道文件成功"<<endl;

    close(rfd);
    cout<<"关闭读端管道文件成功"<<endl;
    sleep(2);
    return 0;
}